package com.example.lin.day8_30;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.example.lin.day8_30.db.HelloWorldOpenHelper;
import com.example.lin.day8_30.pojo.Student;

import java.util.List;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private ListView lv_show;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        lv_show = findViewById(R.id.lv_show);
        MyCursorAdapter myCursorAdapter = new MyCursorAdapter(this);
        lv_show.setAdapter(myCursorAdapter);
        Cursor cursor = HelloWorldOpenHelper.getInstance(this).queryAllReturnCursor();
        //数据更新
        myCursorAdapter.swapCursor(cursor);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.m1:
                insertData();
                break;
            case R.id.m2:
                HelloWorldOpenHelper.getInstance(this).delete(1);
                break;
            case R.id.m3:
                HelloWorldOpenHelper.getInstance(this).update(2, new Student(33, "王五", 155, "女"));
                break;
            case R.id.m4:
                break;
            case R.id.m5:
                List<Student> students = HelloWorldOpenHelper.getInstance(this).queryAll();
                for (Student s : students) {
                    Log.i(TAG, "onOptionsItemSelected: " + s);
                }
                break;
            case R.id.m6:
                break;
        }
        return super.onOptionsItemSelected(item);
    }


    private void insertData() {
        for (int i = 0; i < 50; i++) {
            Student student = new Student(22 + i, "李四" + i, 155.5 + i % 20, i % 2 == 0 ? "男" : "女");
            HelloWorldOpenHelper.getInstance(this).insert(student);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return super.onCreateOptionsMenu(menu);
    }

//    /**
//     * 创建数据库
//     *
//     * @param view
//     */
//    public void test1(View view) {
//        // 创建该对象并不会创建数据库和数据表
//        HelloWorldOpenHelper helloWorldOpenHelper = HelloWorldOpenHelper.getInstance(this);
//        //如果是第一次安装App,则第一次调用该方法的时候,数据库的 onCreate 将被调用.
//        //如果是更新App后,且数据库版本发生改变,则,第一次调用该方法的时候,数据库的 onUpgrade 将被调用.
//        SQLiteDatabase db = helloWorldOpenHelper.getReadableDatabase();
//    }


}
